import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
import {throwError} from 'rxjs';
import {catchError, retry} from 'rxjs/operators';

import * as C from '../global/config';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

  constructor() {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler) {

    // 获取token
    let token = '';
    const loginInfo = localStorage.getItem('login_info');
    if (loginInfo !== null) {
      const info = JSON.parse(loginInfo);
      if (info.token !== null && info.token !== '') {
        token = `Bearer ${info.token}`;
      }
    }

    // 设置请求头
    const newReq = req.clone({
      url: `${C.basePath}${req.url}`,
      setHeaders: {
        ['Authorization']: token
      }
    });

    // send cloned request with header to the next handler.
    return next.handle(newReq)
      .pipe(
        retry(0),
        catchError(this.handleError)
      );

  }

  private handleError(error: HttpErrorResponse) {
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: `, error.error);
    switch (error.status) {
      case 401:
        console.error('请先登录');
        break;
      case 403:
        console.error('权限不足');
        break;
      case 404:
        console.error('请求的路径错误');
        break;
      case 500:
        console.error('请求的服务器错误');
        break;
      default:
        break;
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }

}
